package org.wmq.shopmanager.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.wmq.commonutil.constant.RedisConstant;
import org.wmq.commonutil.context.SystemUserHolder;
import org.wmq.commonutil.result.Result;
import org.wmq.shopmanager.mapper.SystemUserMapper;
import org.wmq.shopmanager.service.SystemUserService;
import org.wmq.shopmodel.DTO.system.LoginDTO;
import org.wmq.shopmodel.DTO.system.SystemUserQueryDTO;
import org.wmq.shopmodel.Entity.system.SystemUser;
import org.wmq.shopmodel.VO.system.LoginVO;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper,SystemUser> implements SystemUserService {
    private final SystemUserMapper systemUserMapper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public Result<LoginVO> login(LoginDTO loginDTO) {
        String codeKey = loginDTO.getCodeKey();
        if (codeKey == null){
            return Result.error("验证码不能为空");
        }
        String cachedCodeValue = this.redisTemplate.opsForValue().get(RedisConstant.VALIDATE_CODE_CACHE_PREFIX + codeKey);
        if (cachedCodeValue == null){
            return Result.error("验证码已过期");
        }
        if (!cachedCodeValue.equals(loginDTO.getCaptcha())){
            return Result.error("验证码错误");
        }
        this.redisTemplate.delete(RedisConstant.VALIDATE_CODE_CACHE_PREFIX + codeKey);
        SystemUser systemUser = this.getSystemUserByUsername(loginDTO.getUsername());
        if (systemUser == null){
            return Result.error("用户名不存在");
        }
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginDTO.getPassword()))){
            return Result.error("密码错误");
        }
        String token = UUID.randomUUID().toString();
        this.redisTemplate.opsForValue().set(token, JSON.toJSONString(systemUser), RedisConstant.LOGIN_USER_INFO_EXPIRE_MS, TimeUnit.MILLISECONDS);

        LoginVO result = new LoginVO();
        result.setToken(token);
        return Result.success(result);
    }

    @Override
    public SystemUser getSystemUserInfo() {
        return SystemUserHolder.get();
    }

    @Override
    public void logout(String token) {
        this.redisTemplate.delete(RedisConstant.LOGIN_USER_INFO_CACHE_PREFIX + token);
    }

    @Override
    public IPage<SystemUser> getPageItem(SystemUserQueryDTO systemUserQueryDTO) {
        Page<SystemUser> page = new Page<>(systemUserQueryDTO.getPageNo(),systemUserQueryDTO.getPageSize());
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        String keyword = systemUserQueryDTO.getKeyword();
        if (StringUtils.isNotEmpty(keyword)){
            queryWrapper.like(SystemUser::getName,keyword);
        }
        LocalDateTime createTimeBegin = systemUserQueryDTO.getCreateTimeBegin();
        if (createTimeBegin != null){
            queryWrapper.ge(SystemUser::getCreateTime,createTimeBegin);
        }
        LocalDateTime createTimeEnd = systemUserQueryDTO.getCreateTimeEnd();
        if (createTimeEnd != null){
            queryWrapper.le(SystemUser::getCreateTime,createTimeEnd);
        }
        return this.page(page,queryWrapper);
    }

    @Override
    public Result<Void> saveSystemUser(SystemUser systemUser) {
        if (StringUtils.isBlank(systemUser.getName())){
            return Result.error("用户名不能为空");
        }
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getName,systemUser.getName());
        if (this.systemUserMapper.selectCount(queryWrapper) > 0){
            return Result.error("用户名已存在");
        }
        String password = systemUser.getPassword();
        if (StringUtils.isBlank(password)){
            return Result.error("密码不能为空");
        }
        systemUser.setPassword(DigestUtils.md5Hex(password));
        this.systemUserMapper.insert(systemUser);
        return Result.success();
    }

    @Override
    public Result<Void> updateSystemUserById(SystemUser systemUser) {
        if (systemUser.getId() == null){
            return Result.error("用户ID不能为空");
        }
        String name = systemUser.getName();
        if (StringUtils.isBlank(name)){
            return Result.error("用户名不能为空");
        }
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getName,name);
        if (this.systemUserMapper.selectCount(queryWrapper) > 0){
            return Result.error("用户名已存在");
        }
        String password = systemUser.getPassword();
        if (password == null){
            //that is ok
        }else if (password.equals("")){
            return Result.error("密码不能为空");
        }else{
            systemUser.setPassword(DigestUtils.md5Hex(password));
        }
        this.systemUserMapper.updateById(systemUser);
        return Result.success();
    }

    private SystemUser getSystemUserByUsername (String username){
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername,username);
        return this.systemUserMapper.selectOne(queryWrapper);
    }
}
